package study.仪器解析.串口化通信.生化仪;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import study.仪器解析.串口化通信.生化仪.entity.TotalRecord;
import study.仪器解析.串口化通信.生化仪.entity.HeaderRecord;
import study.仪器解析.串口化通信.生化仪.entity.OrderRecord;
import study.仪器解析.串口化通信.生化仪.entity.PatientRecord;
import study.仪器解析.串口化通信.生化仪.entity.QueryRecord;
import study.仪器解析.串口化通信.生化仪.entity.ResultRecord;
import study.仪器解析.串口化通信.生化仪.entity.TerminationRecord;
import study.utils.SplitUtils ;

import java.util.*;
@Slf4j
public class ASTMParser3 {

    public List<TotalRecord> parseASTMMessage(String astmData) {

        // 除去STX（02），ETX（03），EOT（04）
        // 分割STX
        // 按记录拆分数据
        List<TotalRecord> totalRecords = new ArrayList<>();

        String[] records = astmData.split("\\[STX]");
        Map<Integer,List<String>> recordMap = new HashMap<>();
        Integer size = 1;
        recordMap.put(1,new ArrayList<String>());
        for (String record : records) {
            List<String> recordList = recordMap.get(size);
            System.out.println("record:" + record);
            if(record.trim().length() == 0){
                continue;
            }
            // 分割CR ETX
            String[] split = record.split("\\[CR]\\[ETX]");
            System.out.println("校验码：" +split[1]);
            // trim方法会去除CR，LF，ETX，STX，EOT等标识符
            record = split[0].trim();
            recordList.add(record);
            System.out.println("data:" + record);
            recordMap.put(size,recordList);
            if(record.charAt(1) == 'L'){
                recordMap.put(++size,new ArrayList<String>());
            }
        }

        for (Integer integer : recordMap.keySet()) {
            List<String> list = recordMap.get(integer);
            TotalRecord totalRecord = new TotalRecord();
            if(list.size() == 0){
                continue;
            }
            for (String record : list) {
                char recordType = record.charAt(1);


                // 根据类型进行分类处理

                switch (recordType) {
                    case 'H':
                        totalRecord.setHeaderRecord(parseHeaderRecord(record));
                        break;
                    case 'P':
                        totalRecord.setPatientRecord(parsePatientRecord(record));
                        break;
                    case 'O':
                        totalRecord.setOrderRecord(parseOrderRecord(record));
                        break;
                    case 'R':
                        totalRecord.setResultRecord(parseResultRecord(record));
                        break;
                    case 'Q':
                        totalRecord.setQueryRecord(parseQueryRecord(record));
                        break;
                    case 'L':
                        totalRecord.setTerminationRecord(parseTerminationRecord(record));
                        break;
                    default:
                        System.out.println("未知记录类型: " + recordType);
                }
            }
            totalRecords.add(totalRecord);
        }
        log.info("totalRecords:{}",totalRecords);
        return totalRecords;
    }

    private HeaderRecord parseHeaderRecord(String record) {
        // 示例: H|\^&|||Analyzer|||||Host|||1|20081124151206
        String[] fields = SplitUtils.splitVerticalBar(record);
        HeaderRecord headerRecord = new HeaderRecord();
        headerRecord.setSenderNameOrId(fields[4]);
        headerRecord.setReceiverId(fields[9]);
        headerRecord.setVersionNo(fields[11]);
        headerRecord.setDateTime(fields[12]);
        System.out.println("Header Record:");
        System.out.println("Delimiter Definition:" + fields[1]);
        System.out.println("Sender Name or ID: " + fields[4]);
        System.out.println("Receiver ID: " + fields[9]);
        System.out.println("Version No: " + fields[11]);
        System.out.println("Date and Time of Message: " + fields[12]);
        System.out.println();
        return headerRecord;
    }

    private PatientRecord parsePatientRecord(String record) {
        // 示例: P|1||||ZhangDongdong|||M||||||40^Y
        String[] fields = SplitUtils.splitVerticalBar(record);
        String[] ageInfo = new String[0];
        String age = null;
        String ageUnit = null;
        if(!ObjectUtils.isEmpty(fields[14])) {
            ageInfo = SplitUtils.splitLatticeSymbol(fields[14]);
            System.out.println("AgeInfo: {");
            if (ageInfo.length > 0) {
                age = ageInfo[0];
                ageUnit = ageInfo[1];
            }
        }
        PatientRecord patientRecord = new PatientRecord();
        patientRecord.setSequenceNumber(fields[1]);
        patientRecord.setPatientName(fields[5]);
        patientRecord.setSex(fields[8]);
        Optional.ofNullable(age).ifPresent(patientRecord::setAge);
        Optional.ofNullable(ageUnit).ifPresent(patientRecord::setAgeUnit);
        System.out.println("Patient Record:");
        System.out.println("Sequence Number: " + fields[1]);
        System.out.println("Patient Name: " + fields[5]);
        System.out.println("Sex: " + fields[8]);
        System.out.println("AgeInfo: {");
        System.out.println(" Age: " + age);
        System.out.println(" AgeUnit:"+ ageUnit);
        System.out.println("}");
        System.out.println();
        return patientRecord;
    }

    private OrderRecord parseOrderRecord(String record) {
        /*样品编号([样品编号]^[样品编号]^[磁盘编号]^[位置编号]^[稀释剂])*/
        // 示例: O|1|^1^1^10^N|||R|20081124151012|||||||||1||||||||||O
        String[] fields = SplitUtils.splitVerticalBar(record);
        OrderRecord orderRecord = new OrderRecord();
        orderRecord.setSequenceNumber(fields[1]);
        String[] specimenInfo = SplitUtils.splitLatticeSymbol(fields[2]);
        orderRecord.setSampleId(specimenInfo[0]);
        orderRecord.setSampleNo(specimenInfo[1]);
        orderRecord.setDiskId(specimenInfo[2]);
        orderRecord.setPositionNo(specimenInfo[3]);
        if(!ObjectUtils.isEmpty(fields[3])){
            String[] instrumentOrSpecimenInfo = SplitUtils.splitLatticeSymbol(fields[3]);
            orderRecord.setQcName(instrumentOrSpecimenInfo[0]);
            orderRecord.setQcLotNo(instrumentOrSpecimenInfo[1]);
        }
        orderRecord.setPriority(fields[5]);
        orderRecord.setDateTime(fields[6]);
        orderRecord.setSpecimenDescriptor(fields[15]);
        orderRecord.setReportTypes(fields[25]);

        System.out.println("Order Record:");
        System.out.println("Sequence Number: " + fields[1]);

        System.out.println("SpecimenInfo: {");
        //样本结果：条形码号
        System.out.println(" Sample ID: "+ specimenInfo[0] );
        //样本结果：样本编号
        System.out.println(" Sample No: "+ specimenInfo[1] );
        System.out.println(" Disk ID: "+ specimenInfo[2] );
        System.out.println(" Position No: "+ specimenInfo[3] );
//        System.out.println(" Diluent: "+ specimenInfo[4] );
        System.out.println("}");

        System.out.println("instrumentOrSpecimenInfo: {");
        if(!ObjectUtils.isEmpty(fields[3])){
            String[] instrumentOrSpecimenInfo = SplitUtils.splitLatticeSymbol(fields[3]);

            System.out.println(" Qc Name: "+ instrumentOrSpecimenInfo[0] );
            System.out.println(" Qc Lot No: "+ instrumentOrSpecimenInfo[1] );
        }
        System.out.println("}");
        System.out.println("Priority: " + fields[5]);
        System.out.println("Requested/Ordered Date and Time: " + fields[6]);
        System.out.println("Specimen Descriptor: " + fields[15]);
        System.out.println("Report Types: " + fields[25]);
        System.out.println();
        return orderRecord;
    }

    private ResultRecord parseResultRecord(String record) {
        // 示例: R|1|^^^GGT|4.96|mg/dL|3^12\0^20|N||F||||20081124151012
        String[] fields = SplitUtils.splitVerticalBar(record);
        String[] universalTestIDInfo = SplitUtils.splitLatticeSymbol(fields[2]);
        String[] referenceRangesInfo;
        if(fields[5].contains("\\")){
            referenceRangesInfo = fields[5].split("\\\\");
        }else {
            referenceRangesInfo = SplitUtils.splitLatticeSymbol(fields[5]);

        }
        System.out.println("Result Record:");
        ResultRecord resultRecord = new ResultRecord();
        resultRecord.setSequenceNumber(fields[1]);
        resultRecord.setUniversalTestId(universalTestIDInfo[universalTestIDInfo.length-1]);
        resultRecord.setMeasurementValue(fields[3]);
        resultRecord.setUnit(fields[4]);
        resultRecord.setNormalRange(referenceRangesInfo[0]);
        resultRecord.setCriticalRange(referenceRangesInfo[1]);
        resultRecord.setResultAbnormalFlags(fields[6]);
        resultRecord.setNatureOfAbnormalityTesting(fields[7]);
        resultRecord.setResultStatus(fields[8]);
        resultRecord.setDateTime(fields[12]);
        System.out.println("Sequence Number: " + fields[1]);
        // 发送样本结果时，为项目简称
        System.out.println("Universal Test ID: " + universalTestIDInfo[universalTestIDInfo.length-1]);
        System.out.println("Test Result: " + fields[3] + " " + fields[4]);

        System.out.println("referenceRangesInfo: {");
        if(fields[5].contains("\\")){
            System.out.println(" normal range:" + referenceRangesInfo[0]);
            System.out.println(" critical range:" + referenceRangesInfo[1]);
        }else {
            System.out.println(" target mean:" + referenceRangesInfo[0]);
            System.out.println(" target SD:" + referenceRangesInfo[1]);
        }
        System.out.println("}");

        System.out.println("Result Abnormal Flags: " + fields[6]);
        System.out.println("Nature of Abnormality Testing: " + fields[7]);
        System.out.println("Result Status: " + fields[8]);
        System.out.println("Date/Time Test Completed: " + fields[12]);
        System.out.println();
        return resultRecord;
    }

    private QueryRecord parseQueryRecord(String record) {
        // 示例: Q|1|^1^0^1^N| |ALL||||||||O
        String[] fields = SplitUtils.splitVerticalBar(record);
        String[] startingRangeIDInfo = SplitUtils.splitLatticeSymbol(fields[2]);
        System.out.println("Query Record:");
        QueryRecord queryRecord = new QueryRecord();
        queryRecord.setSequenceNumber(fields[1]);
        queryRecord.setSampleId(startingRangeIDInfo[0]);
        queryRecord.setSampleNo(startingRangeIDInfo[1]);
        queryRecord.setDiskId(startingRangeIDInfo[2]);
        queryRecord.setPositionNo(startingRangeIDInfo[3]);
        queryRecord.setDiluent(startingRangeIDInfo[4]);
        queryRecord.setUniversalTestId(fields[4]);
        queryRecord.setRequestInformationStatusCodes(fields[12]);
        System.out.println("Sequence Number: " + fields[1]);
        System.out.println("startingRangeIDInfo: {");
        System.out.println(" Sample ID: " + startingRangeIDInfo[0]);
        System.out.println(" Sample No: " + startingRangeIDInfo[1]);
        System.out.println(" Disk ID: " + startingRangeIDInfo[2]);
        System.out.println(" Position No: " + startingRangeIDInfo[3]);
        System.out.println(" Diluent: " + startingRangeIDInfo[4]);
        System.out.println("}");

        System.out.println("Universal Test ID: " + fields[4]);
        System.out.println("Request Information Status Codes: " + fields[12]);
        System.out.println();
        return queryRecord;
    }

    private TerminationRecord parseTerminationRecord(String record) {
        // 示例: L|1|N
        String[] fields = SplitUtils.splitVerticalBar(record);
        TerminationRecord terminationRecord = new TerminationRecord();
        terminationRecord.setSequenceNumber(fields[1]);
        terminationRecord.setTerminationCode(fields[2]);
        System.out.println("Termination Record:");
        System.out.println("Sequence Number: " + fields[1]);
        System.out.println("Termination Code: " + fields[2]);
        System.out.println();
        return terminationRecord;
    }

}